<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input clearable
                    @clear="getUserList"
                    v-model="queryInfo.query"
                    placeholder="请输入内容">
            <el-button @click="getUserList"
                       slot="append"
                       icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList"
                border
                stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名"
                         prop="mgName"></el-table-column>
        <el-table-column label="邮箱"
                         prop="mgEmail"></el-table-column>
        <el-table-column label="电话"
                         prop="mgMobile"></el-table-column>
        <el-table-column label="角色"
                         prop="roleName"></el-table-column>
        <el-table-column label="状态"
                         prop="mgState">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mgState"
                       :active-value="1"
                       :inactive-value="0"
                       @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.mgId)"></el-button>
            <!-- 删除 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeUserById(scope.row.mgId)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark"
                        content="分配角色"
                        placement="top">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNum"
                     :page-sizes="[2, 5, 10, 20]"
                     :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="40%"
               @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="mgName">
          <el-input v-model="addForm.mgName"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="mgPwd">
          <el-input v-model="addForm.mgPwd"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="mgEmail">
          <el-input v-model="addForm.mgEmail"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mgMobile">
          <el-input v-model="addForm.mgMobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog title="修改用户"
               :visible.sync="editDialogVisible"
               width="40%"
               @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form ref="editFormRef"
               :model="editForm"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.mgName"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.mgEmail"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="editForm.mgMobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色"
               :visible.sync="setRoleDialogVisible"
               width="40%"
               @close="setRoleDialogClosed">
      <div>
        <p>当前用户：{{userInfo.mgName}}</p>
        <p>当前角色：{{userInfo.roleName}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId"
                     placeholder="请选择">
            <el-option v-for="item in rolesList"
                       :key="item.roleId"
                       :label="item.roleName"
                       :value="item.roleId"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法的邮箱！'))
      }
    }

    // 邮箱手机号规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        return callback(new Error('请输入合法的手机号码！'))
      }
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        psName: '',
        // 当前页
        pageNum: 1,
        // 每页显示多少条
        pageSize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框
      addDialogVisible: false,
      // 控制修改用户对话框
      editDialogVisible: false,
      // 控制分配角色对话框
      setRoleDialogVisible: false,
      // 添加用户
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户对象
      editForm: {

      },
      // 添加用户表单的验证规则
      addFormRules: {
        mgName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 11, message: '用户名应在3到11个字符之间', trigger: 'blur' }
        ],
        mgPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 11, message: '密码应在6到15个字符之间', trigger: 'blur' }
        ],
        mgEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mgMobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 需分配角色的用户信息
      userInfo: {},
      // 可分配角色数据列表
      rolesList: [],
      // 已选中角色id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.post('/api/manager/getByParam?pageNum=' + this.queryInfo.pageNum + '&pageSize=' + this.queryInfo.pageSize, { psName: this.queryInfo.psName })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      } else {
        this.userList = res.data.list
        this.total = res.data.total
      }
    },
    // 监听pagesize改变
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 监听页码值改变
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    // 监听状态开关
    async userStateChange (userInfo) {
      const { data: res } = await this.$http.put('/api/manager/state?mgId=' + userInfo.mgId + '&mgState=' + userInfo.mgState)
      if (res.meta.status !== 203) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      } else {
        return this.$message.success('更新用户状态成功！')
      }
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/manager/add', this.addForm)
        if (res.meta.status !== 200) {
          this.$message.error('添加用户失败！')
        } else {
          this.$message.success('添加用户成功！')
          this.addDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 展示修改用户对话框
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('api/manager/getById?mgId=' + id)
      if (res.meta.status !== 207) {
        return this.$message.error('查询用户信息失败！')
      } else {
        this.editForm = res.data
      }
    },
    // 修改用户
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/api/manager/updById', { mgId: this.editForm.mgId, mgEmail: this.editForm.mgEmail, mgMobile: this.editForm.mgMobile })
        if (res.meta.status !== 203) {
          return this.$message.error('更新用户信息失败:' + res.meta.msg)
        } else {
          this.editDialogVisible = false
          this.getUserList()
          return this.$message.success('更新用户信息成功！')
        }
      })
    },
    // 根据id删除用户信息
    async removeUserById (mgId) {
      // 弹框确认
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      } else {
        const { data: res } = await this.$http.delete('api/manager/delById?mgId=' + mgId)
        if (res.meta.status !== 205) {
          return this.$message.error('删除用户失败：' + res.meta.msg)
        } else {
          this.getUserList()
          return this.$message.success('删除用户成功！')
        }
      }
    },
    // 展示分配角色对话框
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 获取所有角色列表
      const { data: res } = await this.$http.get('/api/roles/getRoleList')
      if (res.meta.status !== 207) {
        return this.$message.error('获取可分配角色列表失败！')
      } else {
        this.rolesList = res.data
      }
      this.setRoleDialogVisible = true
    },
    // 保存分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      } else {
        const { data: res } = await this.$http.put('/api/manager/updRole?mgId=' + this.userInfo.mgId + '&roleId=' + this.selectedRoleId)
        if (res.meta.status !== 203) {
          return this.$message.error(res.meta.msg)
        } else {
          this.getUserList()
          this.setRoleDialogVisible = false
          return this.$message.success('分配角色成功！')
        }
      }
    },
    // 监听分配角色对话框关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }

}
</script>

<style lang="less" scoped>
</style>
